from django.shortcuts import get_object_or_404
from django.http import Http404
from django.core.exceptions import ValidationError
from django import forms

from .models import Question, Choice


def question_pk_validator(pk):
    try:
        get_object_or_404(Question, pk=pk)
    except Http404:
        raise ValidationError('question not exists')


def choice_pk_validator(pk):
    try:
        get_object_or_404(Choice, pk=pk)
    except Http404:
        raise ValidationError('choice not exists')


class ChoiceField(forms.IntegerField):

    def to_python(self, value):
        if isinstance(value, list):
            value = value[0]
        return forms.IntegerField.to_python(self, value)


class VoteForm(forms.Form):
    question = forms.IntegerField(validators=[question_pk_validator])
    choice = ChoiceField(validators=[choice_pk_validator])

    def clean(self):
        q = self.cleaned_data['question']
        c = self.cleaned_data.get('choice')
        if not c:
            raise ValidationError('no choice selected')
        choice = Choice.objects.get(pk=c)
        if choice.question.pk != q:
            msg = 'choice #%s not belongs to question #%s' % (c, q)
            raise ValidationError(msg)
        return self.cleaned_data


class SignupForm(forms.Form):
    name = forms.CharField(max_length=8)
    password = forms.CharField(min_length=8)


class LoginForm(forms.Form):
    name = forms.CharField(max_length=8)
    password = forms.CharField(max_length=64)
